package com.lgmshare.k3;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lgmshare.component.app.LaraApplication;
import com.lgmshare.component.app.LaraConfiguration;
import com.lgmshare.component.logger.AndroidLogAdapter;
import com.lgmshare.component.logger.CsvFormatStrategy;
import com.lgmshare.component.logger.DiskLogAdapter;
import com.lgmshare.component.logger.FormatStrategy;
import com.lgmshare.component.logger.LogcatLogStrategy;
import com.lgmshare.component.logger.Logger;
import com.lgmshare.component.logger.PrettyFormatStrategy;
import com.lgmshare.component.network.HttpRequestClient;
import com.lgmshare.component.utils.ContextUtils;
import com.lgmshare.component.utils.FileUtils;
import com.lgmshare.k3.helper.PathConfigurationHelper;
import com.lgmshare.k3.helper.StrictModeHelper;
import com.lgmshare.k3.ui.AppUIKit;
import com.lgmshare.k3.utils.AnalyticsUtils;

import java.lang.ref.WeakReference;

public class K3Application extends LaraApplication {

    private static K3Application mApplication;
    //为避免内存泄漏使用弱引用
    private WeakReference<Activity> mCurrentActivity;

    private AppUIKit mAppUIKit;

    public static K3Application getInstance() {
        return mApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        //初始化服务
        if (ContextUtils.isMainProcess(this)) {
            initLogger();
            initFileDirs();
            initActivityLifecycleCallback();
            HttpRequestClient.init(this);
            mAppUIKit = new AppUIKit();
            mAppUIKit.init(this);
        }
        //严格模式
        StrictModeHelper.setPolicy(K3Config.DEBUG_MODE);
    }

    @Override
    public LaraConfiguration onBuildFrameConfiguration() {
        return new LaraConfiguration.Builder()
                .enableDebugModel(K3Config.DEBUG_MODE)
                .build();
    }

    private void initLogger() {
        //日志显示策略
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(0)         // (Optional) How many method line to show. Default 2
                .methodOffset(5)        // (Optional) Hides internal method calls up to offset. Default 5
                .format(false)
                .logStrategy(new LogcatLogStrategy()) // (Optional) Changes the log strategy to print out. Default LogCat
                .tag(BuildConfig.APPLICATION_ID)   // (Optional) Global tag for every log. Default PRETTY_LOGGER
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public void log(int priority, @Nullable String tag, @NonNull String message) {
                super.log(priority, tag, message);
                // 将错误信息发送到友盟
                if (priority > Log.INFO) {
                    AnalyticsUtils.reportError(getApplicationContext(), tag + "###" + message);
                }
            }

            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return K3Config.DEBUG_MODE;
            }
        });
        //日志文件策略
        FormatStrategy diskStrategy = CsvFormatStrategy.newBuilder()
                .folder(PathConfigurationHelper.getLogDir())
                .tag(BuildConfig.APPLICATION_ID).build();
        Logger.addLogAdapter(new DiskLogAdapter(diskStrategy) {

            @Override
            public void log(int priority, @Nullable String tag, @NonNull String message) {
                super.log(priority, tag, message);
            }

            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return K3Config.DEBUG_MODE;
            }
        });
    }

    private void initActivityLifecycleCallback() {
        registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(Activity activity) {
                mCurrentActivity = new WeakReference<>(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    private void initFileDirs() {
        try {
            FileUtils.createFile(PathConfigurationHelper.getLogDir());
            FileUtils.createFile(PathConfigurationHelper.getFileDir());
            FileUtils.createFile(PathConfigurationHelper.getPhotoDir());
        } catch (Exception e) {
            Logger.d(TAG, e.getMessage());
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    /**
     * 当前界面activity
     *
     * @return
     */
    public Activity getCurrentActivity() {
        return mCurrentActivity != null ? mCurrentActivity.get() : null;
    }

    /**
     * 应用退出
     */
    public void exit() {
        System.exit(0);
    }

}
